package cn.yunhe.util;

import cn.yunhe.excep.OutOfNumException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class BingXiangLog {
    int x = 0;

    @Before("p()")
    public void before() {
        System.out.println("前置通知:欢迎光临KK冰箱旗舰店");
    }

    @AfterReturning("p()")
    public void afterReturning(JoinPoint jp) throws OutOfNumException {
        Object[] args = jp.getArgs();
        int k = (int) args[0];
        if (k > 1) {
            throw new OutOfNumException("贪心的客户,特价冰箱只能购买一台");
        }
        System.out.println("后置通知:" + DateFormat.simDate() + ",您成功购买了" + args[0] + "台特价冰箱,欢迎下次光临");
    }

    @AfterThrowing(pointcut = "p()", throwing = "e")
    public void afterThrowing(OutOfNumException e) throws OutOfNumException {
        throw new OutOfNumException("异常通知:" + DateFormat.simDate() + e.getMessage());
    }

    @Around("p()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        Object[] args = pjp.getArgs();
        int buy = (int) args[0];
        if (buy != 1) {
            System.out.println("环绕通知:" + DateFormat.simDate() + ",特价冰箱每人限购1台");
        }
        try {
            if (buy == 0 || buy < 0) {
                throw new OutOfNumException("不买滚");
            } else if (x > 0) {
                throw new OutOfNumException("贪心的客户,特价冰箱只能购买一台");
            }
            return pjp.proceed();
        } finally {
            x++;
        }
    }

    @Pointcut("execution(void saleBX(int))")
    public void p() {
    }
}
